package com.simtop.controller.newrequire;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.User;
import com.simtop.pojo.newrequire.RobotStepScoreVo;
import com.simtop.service.RobotStepScoreService;
import com.simtop.service.UserService;

import com.simtop.util.ExcelUtils;
import com.simtop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author lvyongwei
 * @description 又添加的新需求
 *              1.保留原先的实验报告内容，虽然不会再更改
 *              2.添加新的实验报告内容，因为内容过多，因此一个字段存储在表中
 *              3.要求进入实验前的习题成绩跟每次实验报告对应。因此在用户表中添加了该字段，有此分数则不用每次进去都进行习题操作。
 */
@RestController
@RequestMapping("/newRequire")
@CrossOrigin
public class NewRequireController {

    @Autowired
    private UserService userService;

    @Autowired
    private RobotStepScoreService robotStepScoreService;

    /**
     * 修改用户表中习题成绩字段，该字段不为0，则每次进入实验之前无需做习题
     * @return
     */
    @PostMapping("/updateExercises")
    public ServerResponse<String> updateExercises(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject =JSONObject.parseObject(data);
            Integer exercises = jsonObject.getIntValue("exercises");
            userService.updateExercises(u.getId(),exercises);
            return ServerResponse.createBySuccess("成绩提交成功，该成绩以后一直使用");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("成绩提交失败");
        }
    }


    /**
     * 获取所有实验报告
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/getAllRobotStepScore")
    public ServerResponse<Object> getAllRobotStepScore(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject =JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getIntValue("pageNum");
            Integer pageSize = jsonObject.getIntValue("pageSize");
            //分页
            PageHelper.startPage(pageNum,pageSize);
            List<RobotStepScoreVo> allRobotStepScore = robotStepScoreService.getAllRobotStepScore(u.getRoleId(),u.getId());
            PageInfo<RobotStepScoreVo> pageInfo = new PageInfo<RobotStepScoreVo>(allRobotStepScore);
            return ServerResponse.createBySuccess(pageInfo);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("获取成绩列表失败");
        }
    }

    /**
     * 教师评价和心得体会
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/updateRobotStepScore")
    public ServerResponse<Object> updateRobotStepScore(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject =JSONObject.parseObject(data);
            Long scoreId = jsonObject.getLong("scoreId");
            Integer commitScore = jsonObject.getInteger("commitScore");
            String evaluation = jsonObject.getString("evaluation");
            robotStepScoreService.updateRobotStepScore(scoreId,commitScore,evaluation);
            return ServerResponse.createBySuccessMsg("教师评价成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("教师评价失败");
        }
    }

    /**
     * 导出实验成绩新表
     * @param response
     */
    @GetMapping("/exportScore")
    public void exportScore(HttpServletResponse response){
        ServletOutputStream out = null;
        List<RobotStepScoreVo> robotStepScoreVos = robotStepScoreService.exportScore();
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "实验成绩";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelUtils.writeExcel(out, RobotStepScoreVo.class,robotStepScoreVos);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 教师评价和心得体会
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/deleteScore")
    public ServerResponse<Object> deleteScore(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject =JSONObject.parseObject(data);
            Long scoreId = jsonObject.getLong("id");
            robotStepScoreService.deleteScore(scoreId);
            return ServerResponse.createBySuccessMsg("删除实验成绩成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("删除实验成绩失败");
        }
    }
}
